package org.matomo.sdk.extra;

import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.app.Context;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.CommonEventSubscriber;
import ohos.rpc.RemoteException;
import org.matomo.sdk.Matomo;

import java.util.Collections;
import java.util.List;

public class InstallReferrerReceiver extends CommonEventSubscriber {
    private static final String TAG = Matomo.tag(InstallReferrerReceiver.class);

    // Google Play
    private static final String REFERRER_SOURCE_GOOGLE_PLAY = "com.android.vending.INSTALL_REFERRER";
    private static final String ARG_KEY_GOOGLE_PLAY_REFERRER = "referrer";

    static final String PREF_KEY_INSTALL_REFERRER_EXTRAS = "referrer.extras";
    static final List<String> RESPONSIBILITIES = Collections.singletonList(REFERRER_SOURCE_GOOGLE_PLAY);
    private Context mContext;

    public InstallReferrerReceiver(CommonEventSubscribeInfo info, Context context) {
        super(info);
        mContext = context;
    }

    @Override
    public void onReceiveEvent(CommonEventData commonEventData) {
        Intent intent = commonEventData.getIntent();
        if (intent.getAction() == null || !RESPONSIBILITIES.contains(intent.getAction())) {
            return;
        }
        if (intent.getBooleanParam("forwarded", false)) {
            return;
        }
        if (intent.getAction().equals(REFERRER_SOURCE_GOOGLE_PLAY)) {
            String referrer = intent.getStringParam(ARG_KEY_GOOGLE_PLAY_REFERRER);
            if (referrer != null) {
                Matomo.getInstance(mContext.getApplicationContext()).getPreferences().putString(PREF_KEY_INSTALL_REFERRER_EXTRAS, referrer).flushSync();
            }
        }

        Operation operation = new Intent.OperationBuilder()
                .withAction(mContext.getBundleName())
                .build();
        intent.setParam("forwarded", true);
        intent.setOperation(operation);
        CommonEventData eventData = new CommonEventData(intent);
        try {
            CommonEventManager.publishCommonEvent(eventData);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
